package edu.whut.andrecorder;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.view.View.OnClickListener; 

public class AndrecorderFileExplore extends ListActivity
{
	private List<String> items=null;
	private List<String> paths=null;
	private TextView curPathShow=null;
	private File curFile=new File("/sdcard");
	private String rootPath="/sdcard";
	
	@Override
	protected void onCreate(Bundle icicle)
	{
		super.onCreate(icicle);
		setContentView(R.layout.file_explorer);
		fill(new File(rootPath).listFiles());
		curPathShow=(TextView)findViewById(R.id.curPathShow);
		curPathShow.setText("当前目录:"+rootPath);
		
		//路径选择确定按钮
		Button pathConfirmBtn=(Button)findViewById(R.id.pathConfirmBtn);
		pathConfirmBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Intent selecPath=new Intent(AndrecorderFileExplore.this,AndrecorderSetting.class);
				selecPath.putExtra("filepath",curFile.getAbsolutePath());
				setResult(1,selecPath);
				finish();
			}
		});
		//路径选择取消按钮
		Button pathCancleBtn=(Button)findViewById(R.id.pathCancleBtn);
		pathCancleBtn.setOnClickListener(new OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				setResult(2);
				finish();
			}
		});
	}
	
	protected void onListItemClick(ListView l, View v, int position, long id)
	{
		super.onListItemClick(l, v, position, id);
		int selectPostionID=(int)position;
		File file=new File(paths.get(selectPostionID));
		
		//点击'返回上一�?条目且当前目录不为根,则返回父目录
		if(!curFile.getPath().equals("/sdcard")&&selectPostionID==0)
		{
			curFile=curFile.getParentFile();
			curPathShow.setText("当前目录:"+curFile.getAbsolutePath());
			fill(curFile.listFiles());
		}
		//否则打开
		else if (file.isDirectory())
		{
			curPathShow.setText("当前目录:"+file.getAbsolutePath());
			curFile=file;
			fill(file.listFiles());
		}
	}
	
	//打开目录方法
	private void fill(File[] files)
	{
		items=new ArrayList<String>();//目录
		paths=new ArrayList<String>();//目录路径
		
		for (File file:files)
			//不以...的目录则加入列表
			if(file.isDirectory()&&file.getName().indexOf(".")!=0)
			{
				items.add(file.getName());
				paths.add(file.getPath());
			}
		//当前目录不问根则添加'返回上一层目录'
		if(!curFile.getPath().equals(rootPath))
		{
			items.add(0, "返回上一层");
			paths.add(0, curFile.getParent());
		}
		setListAdapter(new ArrayAdapter<String>(this, R.layout.file_row,items));
	}
}